/* eslint-disable new-cap */
import Taro from '@tarojs/taro';

const STORAGE = {
  key_token: '__p8hcare_token',
  login_state: '__p8hcare_loginState',
  // key_postid:"__p8hcare_postid",
};

function setCacheData(obj) {
  if (Taro.getEnv() !== Taro.ENV_TYPE.RN) {
    const { key, data } = obj;
    Taro.setStorageSync(key, data);
  } else {
    Taro.setStorage(obj);
  }
}

function getCacheData(obj) {
  if (Taro.getEnv() !== Taro.ENV_TYPE.RN) {
    const { key } = obj;
    return Taro.getStorageSync(key);
  }
  return Taro.getStorage(obj).then(res => res.data);
}

export default class storage {
  constructor() {
    this.instance = null;
    this.mToken = null;
    this.loginState = '';
    this.scrollLog = false;
    // this.mIdentify = null;
    // this.postId =null;
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new storage();
    }
    return this.instance;
  }

  initModel = () => {
    if (this.mToken) return Promise.resolve();
    return Promise.all([
      this.initToken(),
      this.initLoginState(),
    ]);
  };

  initToken = async () => {
    const token = await getCacheData({ key: STORAGE.key_token });
    this.mToken = token;
  };

  setToken(data) {
    this.mToken = data;
    return setCacheData({ key: STORAGE.key_token, data });
  }

  getToken() {
    // let token = this.mToken;
    /* if (!token) {
      token = getCacheData({ key: STORAGE.key_token });
      this.mToken = token;
    } */
    return this.mToken;
  }

  initLoginState = async () => {
    this.loginState = await getCacheData({ key: STORAGE.login_state });
    return this.loginState;
  };

  setLoginState(data) {
    this.loginState = data;
    return setCacheData({ key: STORAGE.login_state, data });
  }

  async getLoginState() {
    this.loginState = await getCacheData({ key: STORAGE.login_state });
    return this.loginState;
  }

  setLogScroll(scrollAble) {
    this.scrollLog = scrollAble;
  }

  getLogScroll() {
    return this.scrollLog;
  }
}
